package com.mc.mcgoweb;

import com.mc.common.base.BaseResponse;
import com.mc.common.base.ResultUtil;
import com.mc.common.cookie.CookieConstant;
import com.mc.common.cookie.CookieUtil;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.UUID;

/**
 * 卖家用户
 * Created by liuxiaoming
 * 2017-12-06 下午05:35
 */
@SpringBootApplication
@Controller
@RequestMapping("/mc")
public class LoginController {


    @GetMapping("/login")
    @ResponseBody
    public BaseResponse login(@RequestParam("openid") String openid, String password) {
        HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        Cookie cookie = CookieUtil.get(request, CookieConstant.ACCESS_TOKEN);
        //1. openid去和数据库里的数据匹配
        boolean loginFlag = CookieConstant.OPENID.equals(openid) && CookieConstant.PASSWORD.equals(password);
        if (!loginFlag && cookie == null) {
            return ResultUtil.getFailureResultData("请输入密码");
        }
        String sign = request.getHeader("sign");
        //2. 设置token至redis
        String token = UUID.randomUUID().toString();
        Integer expire = CookieConstant.EXPIRE_TIME;
        //3. 设置token至cookie
        CookieUtil.set(response, CookieConstant.ACCESS_TOKEN, token, expire);
        return ResultUtil.getSuccessResultData(token);
    }

    @GetMapping("/logout")
    @ResponseBody
    public BaseResponse logout(
            Map<String, Object> map) {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
        //1. 从cookie里查询
        Cookie cookie = CookieUtil.get(request, CookieConstant.ACCESS_TOKEN);
        if (cookie != null) {
            //2. 清除cookie
            CookieUtil.set(response, CookieConstant.ACCESS_TOKEN, null, 0);
        }

        return ResultUtil.getSuccessResultData();
    }
}